import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { Project, Application, SearchParams, PaginationParams } from '@/types'
import { ApiService } from '@/services/api'

export const useProjectStore = defineStore('project', () => {
  // 状态
  const projects = ref<Project[]>([])
  const applications = ref<Application[]>([])
  const loading = ref(false)
  const totalProjects = ref(0)
  const totalApplications = ref(0)
  
  // 搜索和分页参数
  const searchParams = ref<SearchParams>({
    keyword: '',
    discipline: '',
    enterpriseName: '',
    status: '',
    dateRange: undefined
  })
  
  const paginationParams = ref<PaginationParams>({
    page: 1,
    pageSize: 10,
    total: 0
  })

  // 计算属性
  const publishedProjects = computed(() => 
    projects.value.filter(p => p.status === 'published')
  )
  
  const myApplications = computed(() => 
    applications.value.filter(a => a.applicantId === 'current-user-id') // 这里需要根据实际用户ID过滤
  )

  // 方法
  const fetchProjects = async (params?: SearchParams) => {
    loading.value = true
    try {
      const result = await ApiService.getProjects(params)
      projects.value = result.data
      totalProjects.value = result.total
      return result
    } catch (error) {
      console.error('获取项目列表失败:', error)
      return { data: [], total: 0 }
    } finally {
      loading.value = false
    }
  }

  const fetchApplications = async (params?: any) => {
    loading.value = true
    try {
      const result = await ApiService.getApplications(params)
      applications.value = result.data
      totalApplications.value = result.total
      return result
    } catch (error) {
      console.error('获取申请列表失败:', error)
      return { data: [], total: 0 }
    } finally {
      loading.value = false
    }
  }

  const searchProjects = async (params: SearchParams) => {
    searchParams.value = { ...searchParams.value, ...params }
    paginationParams.value.page = 1 // 重置到第一页
    return await fetchProjects(searchParams.value)
  }

  const createApplication = async (application: Omit<Application, 'id' | 'createdAt' | 'updatedAt'>) => {
    try {
      const newApplication = await ApiService.createApplication(application)
      applications.value.push(newApplication)
      totalApplications.value += 1
      return { success: true, application: newApplication }
    } catch (error) {
      console.error('创建申请失败:', error)
      return { success: false, message: '创建申请失败，请重试' }
    }
  }

  const updateApplicationStatus = async (applicationId: string, status: string) => {
    try {
      const success = await ApiService.updateApplicationStatus(applicationId, status as any)
      if (success) {
        const application = applications.value.find(a => a.id === applicationId)
        if (application) {
          application.status = status as any
          application.updatedAt = new Date().toISOString()
        }
        return { success: true }
      } else {
        return { success: false, message: '更新状态失败' }
      }
    } catch (error) {
      console.error('更新申请状态失败:', error)
      return { success: false, message: '更新状态失败，请重试' }
    }
  }

  const resetSearch = () => {
    searchParams.value = {
      keyword: '',
      discipline: '',
      enterpriseName: '',
      status: '',
      dateRange: undefined
    }
    paginationParams.value.page = 1
  }

  const changePage = (page: number) => {
    paginationParams.value.page = page
    fetchProjects(searchParams.value)
  }

  const changePageSize = (pageSize: number) => {
    paginationParams.value.pageSize = pageSize
    paginationParams.value.page = 1
    fetchProjects(searchParams.value)
  }

  // 初始化
  const initialize = async () => {
    await fetchProjects()
    await fetchApplications()
  }

  return {
    // 状态
    projects,
    applications,
    loading,
    totalProjects,
    totalApplications,
    searchParams,
    paginationParams,
    
    // 计算属性
    publishedProjects,
    myApplications,
    
    // 方法
    fetchProjects,
    fetchApplications,
    searchProjects,
    createApplication,
    updateApplicationStatus,
    resetSearch,
    changePage,
    changePageSize,
    initialize
  }
})
